from tools.tw import jl
import tools.config as cfg
from tools.database import SQLite

dateiv,datetpe,shift,datef = jl.get_current_shift_info()
sd_sql,sd_name=jl.get_shiduan_sql()
print(sd_sql,sd_name)

def main():
    """主函数"""
    # 初始化数据库连接
    db_manager = SQLite(cfg.dbpath)
    if not db_manager.connect():
        print("数据库连接失败")
        return

    try:
        # 获取数据
        var = jl.get_value()
        var_ip = jl.get_ip()
        URL = var.get('webhook', '')
        
        changes = []  # 记录变更信息
        
        # 处理每一行数据
        for i in range(len(var_ip)):
            print(f"正在处理第 {i} 行...")
            
            # 获取当前行的数据
            id_value = var_ip["id"][i]
            workshop = var_ip["workshop"][i]
            line = var_ip["line"][i]
            ip = var_ip["ip"][i]
            segment_path = var_ip["segment_path"][i]
            is_enabled = var_ip["is_enabled"][i]
            active_line_grade = var_ip["current_segment"][i]
            access_path = f"\\\\{ip}{segment_path}"
            
            # 更新数据库并检查是否有变更
            new_grade = update_database(db_manager, id_value, workshop, active_line_grade, is_enabled, ip, access_path, line)
            
            # 检查是否有变更（比较返回的新值与原来的值）
            if new_grade != active_line_grade:
                # 记录变更信息
                change_info = {
                    'id': id_value,
                    'ip': ip,
                    'size': workshop,
                    'line': line,
                    'old_grade': active_line_grade,
                    'new_grade': new_grade,  # 使用函数返回的新值
                    'change_time': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                }
                changes.append(change_info)
                print(f"分档变化记录: {change_info}")

        # 如果有变更，发送通知
        if changes and URL:
            summary = f"【分档变更】共 {len(changes)} 条变化:\n时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
            for change in changes:
                summary += f" 线别: {change['size']}-{change['line']}>>>旧分档: {change['old_grade']}, 新分档: {change['new_grade']};\n"
            
            itw.send_message(URL, summary)
            print("分档变化信息已发送到I通威")
        else:
            print("没有检测到分档变化")

    except Exception as e:
        print(f"发生错误: {e}")
    finally:
        db_manager.close()

if __name__ == "__main__":
    main()